<!--顶部通知组件-->
<template>
  <div>
    <a-popover v-model="visible" trigger="click" placement="bottomRight" :autoAdjustOverflow="true" :arrowPointAtCenter="true"
      overlayClassName="header-notice-wrapper"
      :overlayStyle="{ width: '400px', top: '50px' }">
      <template slot="content">
        <a-spin :spinning="loading">
          <a-tabs>
            <!--通知消息-->
            <a-tab-pane :tab="msg1Title" key="1">
              <a-list>
                <a-list-item :key="index" v-for="(record, index) in notice1">
                  <div style="margin-left: 5%;width: 50%">
                    <p><a @click="showNotice(record)">{{ record.noticeTitle }}</a></p>
                    <p style="color: rgba(0,0,0,.45);margin-bottom: 0px">{{ record.sendTime }} 发布</p>
                  </div>
                  <div style="text-align: right">
                    <p><i class="el-icon-close" @click="ignore(record)"></i></p>
                    <p>
                      <a-tag @click="showNotice(record)" v-if="record.priority === 'L'" color="blue">一般消息</a-tag>
                      <a-tag @click="showNotice(record)" v-if="record.priority === 'M'" color="orange">重要消息</a-tag>
                      <a-tag @click="showNotice(record)" v-if="record.priority === 'H'" color="red">紧急消息</a-tag>
                    </p>
                  </div>
                </a-list-item>
                <div style="margin-top: 5px;text-align: center">
                  <a-button @click="loadData()" type="dashed" block>刷新</a-button>
                  <a-button @click="toMyNotice()" type="dashed" block>查看更多</a-button>
                </div>
              </a-list>
            </a-tab-pane>
            <!--系统消息-->
            <a-tab-pane :tab="msg2Title" key="2">
              <a-list>
                <a-list-item :key="index" v-for="(record, index) in notice2">
                  <div style="margin-left: 5%;width: 50%">
                    <p><a @click="showNotice(record)">{{ record.noticeTitle }}</a></p>
                    <p style="color: rgba(0,0,0,.45);margin-bottom: 0px">{{ record.sendTime }} 发布</p>
                  </div>
                  <div style="text-align: right">
                    <p><i class="el-icon-close" @click="ignore(record)"></i></p>
                    <p>
                      <a-tag @click="showNotice(record)" v-if="record.priority === 'L'" color="blue">一般消息</a-tag>
                      <a-tag @click="showNotice(record)" v-if="record.priority === 'M'" color="orange">重要消息</a-tag>
                      <a-tag @click="showNotice(record)" v-if="record.priority === 'H'" color="red">紧急消息</a-tag>
                    </p>
                  </div>
                </a-list-item>
                <div style="margin-top: 5px;text-align: center">
                  <a-button @click="loadData()" type="dashed" block>刷新</a-button>
                  <a-button @click="toMyNotice()" type="dashed" block>查看更多</a-button>
                </div>
              </a-list>
            </a-tab-pane>
            <!--待办消息-->
            <a-tab-pane :tab="msg3Title" key="3">
              <a-list>
                <a-list-item :key="index" v-for="(record, index) in notice3">
                  <div style="margin-left: 5%;width: 50%">
                    <p><a @click="showNotice(record)">{{ record.noticeTitle }}</a></p>
                    <p style="color: rgba(0,0,0,.45);margin-bottom: 0px">{{ record.sendTime }} 发布</p>
                  </div>
                  <div style="text-align: right">
                    <p><i class="el-icon-close" @click="ignore(record)"></i></p>
                    <p>
                      <a-tag @click="showNotice(record)" v-if="record.priority === 'L'" color="blue">一般消息</a-tag>
                      <a-tag @click="showNotice(record)" v-if="record.priority === 'M'" color="orange">重要消息</a-tag>
                      <a-tag @click="showNotice(record)" v-if="record.priority === 'H'" color="red">紧急消息</a-tag>
                    </p>
                  </div>
                </a-list-item>
                <div style="margin-top: 5px;text-align: center">
                  <a-button @click="loadData()" type="dashed" block>刷新</a-button>
                  <a-button @click="toMyNotice()" type="dashed" block>查看更多</a-button>
                </div>
              </a-list>
            </a-tab-pane>
          </a-tabs>
        </a-spin>
      </template>
      <!--消息icon-->
      <span class="header-notice">
        <a-badge :count="msgTotal">
          <a-icon style="font-size: 16px; padding: 4px" type="bell" />
        </a-badge>
      </span>
    </a-popover>
    <!--普通通知-->
    <show-notice ref="showNotice"></show-notice>
    <!--自定义组件显示通知-->
    <show-dynamic-notice ref="showDynamicNotice" :path="openPath" :componentData="componentData" />
  </div>
</template>

<script>
  import ShowNotice from './ShowNotice'
  import store from '@/store/'
  import ShowDynamicNotice from './ShowDynamicNotice'
  import { listByUser, readNotice } from "@/api/system/notice";

  export default {
    name: "HeaderNotice",
    components: {
      ShowDynamicNotice,
      ShowNotice,
    },
    data() {
      return {
        loading: false,
        visible: false,
        notice1: [],
        notice2: [],
        notice3: [],
        msg1Count: "0",
        msg2Count: "0",
        msg3Count: "0",
        msg1Title: "通知(0)",
        msg2Title: "",
        msg3Title: "",
        stopTimer: false,
        websocket: null,
        lockReconnect: false,
        componentData: {},
        openPath: '',
        msgTotal:0
      }
    },
    computed: {

    },
    mounted() {
      this.loadData();
      this.initWebSocket();
    },
    destroyed: function() { // 离开页面生命周期函数
      this.websocketOnclose();
    },
    methods: {
      /**
       * 加载用户通知
       */
      async loadData() {
        this.loading=true
        // 获取系统消息
        await listByUser().then((res) => {
          this.notice1 = res.data.anntMsgList;
          this.msg1Count = res.data.anntMsgTotal;
          this.msg1Title = "通知(" + res.data.anntMsgTotal + ")";
          this.notice2 = res.data.sysMsgList;
          this.msg2Count = res.data.sysMsgTotal;
          this.msg2Title = "系统消息(" + res.data.sysMsgTotal + ")";
          this.notice3 = res.data.todealMsgList;
          this.msg3Count = res.data.todealMsgTotal;
          this.msg3Title = "待办消息(" + res.data.todealMsgTotal + ")";
          let total = this.msg1Count + this.msg2Count + this.msg3Count;
          this.msgTotal= total
          console.log("未读消息总数",this.msgTotal)
        }).catch(error => {
          this.stopTimer = true;
          console.log("系统消息通知异常", error);
        }).finally(() => {
          this.loading = false;
        });
      },
      /**
       * 忽略消息
       * @param record
       */
      ignore(record){
        readNotice(record.sendId).then((res) => {
          this.loadData();
        });
      },
      /**
       * 显示通知详情
       * @param record
       */
      showNotice(record) {
        readNotice(record.sendId).then((res) => {
            this.loadData();
        });
        this.visible = false;
        if (record.openType === 'component') {
          this.openPath = record.openPage;
          this.componentData = record
          this.$refs.showDynamicNotice.detail();
        } else {
          this.$refs.showNotice.detail(record);
        }
      },
      /**
       * 跳转我的通知
       */
      toMyNotice() {
        this.$router.push({
          path: '/mynotice'
        });
      },
      /**
       * 初始化websoket
       */
      initWebSocket: function() {
        // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
        let uid = store.getters.userId;
        let url = process.env.VUE_APP_WS_API + "/websocket?userId=" + uid;
        console.log("WebSocket连接Url：",url);
        this.websocket = new WebSocket(url);
        this.websocket.onopen = this.websocketOnopen;
        this.websocket.onerror = this.websocketOnerror;
        this.websocket.onmessage = this.websocketOnmessage;
        this.websocket.onclose = this.websocketOnclose;
      },
      websocketOnopen: function() {
        console.log("WebSocket连接成功");
      },
      websocketOnerror: function(e) {
        console.log("WebSocket连接发生错误");
        this.reconnect();
      },
      websocketOnmessage: function(e) {
        console.log("WebSocket接收消息：", e);
        let data = eval("(" + e.data + ")"); //解析对象
        let title
        if (data.cmd == "system") {
          //系统通知
          title='您收到一条新的系统消息'
        } else if (data.cmd == "user") {
          //用户消息
          title='您收到一条新的用户消息'
        } else if (data.cmd == "refresh") {
          this.loadData();
          return
        }
        //延迟查询最新消息，防止数据库事务还未写入
        setTimeout(async() => {
          await this.loadData();
          this.$message.info(title+":"+data.msgTxt);
        }, 3000);
        //再次查询，确保数据稳定
        setTimeout(async() => {
          await this.loadData();
        }, 5000);
      },
      websocketOnclose: function(e) {
        console.log("WebSocket连接关闭 (" + e + ")");
        if (e) {
          console.log("WebSocket连接关闭 (" + e.code + ")");
        }
        this.reconnect();
      },
      /**
       * 发送websoket消息
       * @param text
       */
      websocketSend(text) {
        try {
          this.websocket.send(text);
        } catch (err) {
          console.log("WebSocket发送失败(" + err.code + ")");
        }
      },
      /**
       * 重新连接websoket
       */
      reconnect() {
        const that = this;
        if (that.lockReconnect) return;
        that.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function() {
          console.info("WebSocket尝试重连...");
          that.initWebSocket();
          that.lockReconnect = false;
        }, 5000);
      },
    }
  }
</script>
<style lang="less" scoped>

</style>
